﻿using BCL.WPFComponent.Base;
using Devices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Linq;
using System.Windows.Navigation;

namespace DevicesWPF
{
    /// <summary>
    /// UCSelectDev.xaml 的交互逻辑
    /// </summary>
    public partial class UCSelectDev : BaseShowControl
    {
        public IDevices Device { get; private set; }
         
        public UCSelectDev()
        {
            InitializeComponent();
            
        }

        public override void LanguageBinding()
        {

        }

        private void BaseShowControl_Loaded(object sender, RoutedEventArgs e)
        {
           if(DevicesCollection.Devices==null) 
                return;
            foreach (var item in DevicesCollection.Devices)
            {
                Button button = new Button();
                button.Background = null;
                button.BorderBrush = null;
                UCDevicesState us = new UCDevicesState(item);
                us.Margin = new Thickness(1);
                button.Margin = new Thickness(10, 10, 5, 5);
                button.Content = us;
                button.Click += Button_Click;
                MainPanel.Children.Add(button);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Device = (((Button)sender).Content as UCDevicesState).Dev;
            if (Device.Info.Num == 9)
            {
                Device.AddCommanding -= Device_AddCommanding;
                Device.AddCommanding += Device_AddCommanding;
            }
            MessageBoxResult = MessageBoxResult.OK;
            Window.GetWindow(this)?.Close();
        }

        /// <summary>
        /// 同一类型的不同对象的方法指向不是同一个，所以加static
        /// </summary>
        /// <param name="dev"></param>
        /// <param name="cmd"></param>
        /// <returns></returns>
        private static bool Device_AddCommanding(IDevices dev, Command cmd)
        {
            Devices.Abaxis.Abaxis_Fuse fuse = dev as Devices.Abaxis.Abaxis_Fuse;
            if (cmd.Tests != null && fuse.RequestCodes.Any(o => o.Code == cmd.Tests[0]))
                return true;
            UCDevices.Abaxis.UCFuseItemSelect uCVS2 = new UCDevices.Abaxis.UCFuseItemSelect(dev);
            if (uCVS2.ShowDialog(null) != MessageBoxResult.OK)
                return false;
            cmd.Tests = uCVS2.Tests;
            return true;
        }
    }
}
